<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

// 富文本
import VMdEditor from '@kangc/v-md-editor'
import VMdPreview from '@kangc/v-md-editor/lib/preview'

// 默认图片自备
import defaultBanner from '../assets/note-banner.jpg'
import defaultThumb from '../assets/note-thumb.jpg'

const route = useRoute()
const router = useRouter()
const routeId = route.params.routeId

const routeTitle = ref('')
const routeCoverUrl = ref('') // 路线封面
const notes = ref([])
const selectedNoteId = ref(null)
const selectedNote = ref(null)
const showNoteEditor = ref(false)
const noteEdit = ref({ id: null, title: '', content: '', attachments: [], coverImg: '' })

// 获取当前路线信息
async function fetchRouteTitle() {
  try {
    const res = await axios.get(`/api/route/detail/${routeId}`)
    if (res.data.code === 0) {
      routeTitle.value = res.data.data.title
      routeCoverUrl.value = res.data.data.coverUrl || ''
    }
  } catch {}
}
// 获取笔记
async function fetchNotes() {
  const res = await axios.get(`/api/note/list?routeId=${routeId}`)
  if (res.data.code === 0) {
    notes.value = res.data.data
    if (notes.value.length > 0) selectNote(notes.value[0].id)
    else { selectedNote.value = null; selectedNoteId.value = null }
  }
}
function selectNote(id) {
  selectedNoteId.value = id
  selectedNote.value = notes.value.find(n => n.id === id)
  showNoteEditor.value = false
}
function newNote() {
  noteEdit.value = { id: null, title: '', content: '', attachments: [], coverImg: '' }
  showNoteEditor.value = true
}
async function saveNote() {
  const user = JSON.parse(localStorage.getItem('loginUser'))
  if (!noteEdit.value.title) return ElMessage.warning('标题不能为空')
  try {
    if (noteEdit.value.id) {
      const res = await axios.put('/api/note/update', noteEdit.value)
      if (res.data.code === 0) {
        ElMessage.success('保存成功'); fetchNotes(); showNoteEditor.value = false
      } else ElMessage.error(res.data.msg)
    } else {
      const res = await axios.post('/api/note/add', {
        ...noteEdit.value, routeId: Number(routeId), userId: user?.id || 1
      })
      if (res.data.code === 0) {
        ElMessage.success('添加成功'); fetchNotes(); showNoteEditor.value = false
      } else ElMessage.error(res.data.msg)
    }
  } catch { ElMessage.error('网络异常') }
}
function editNote(note) {
  noteEdit.value = {
    id: note.id,
    title: note.title || note.noteTitle || '',
    content: note.content || note.noteContent || '',
    attachments: note.attachments || [],
    coverImg: note.coverImg || ''
  }
  showNoteEditor.value = true
}
async function deleteNote(id) {
  ElMessageBox.confirm('确定要删除这条笔记吗？', '提示', { type: 'warning' })
      .then(async () => {
        const res = await axios.delete(`/api/note/delete/${id}`)
        if (res.data.code === 0) { ElMessage.success('删除成功'); fetchNotes() }
        else ElMessage.error(res.data.msg)
      })
}
function back() { router.push('/route-list') }
// 富文本图片上传钩子
async function handleUploadImage(files, callback) {
  const formData = new FormData()
  formData.append('file', files[0])
  try {
    const res = await axios.post('/api/file/upload', formData)
    callback([res.data.url])
  } catch { ElMessage.error('图片上传失败') }
}
// 附件上传
async function handleFileUpload(params) {
  const file = params.file
  const formData = new FormData()
  formData.append('file', file)
  try {
    const res = await axios.post('/api/file/upload', formData)
    if (res.data.url) {
      noteEdit.value.attachments = noteEdit.value.attachments || []
      noteEdit.value.attachments.push({
        name: file.name, url: res.data.url, type: file.type
      })
      ElMessage.success('附件上传成功')
    }
  } catch { ElMessage.error('上传失败') }
}
function removeAttachment(idx) { noteEdit.value.attachments.splice(idx, 1) }
// 封面图片上传
async function uploadNoteCover(e) {
  const file = e.target.files[0]
  if (!file) return
  const formData = new FormData()
  formData.append('file', file)
  try {
    const res = await axios.post('/api/file/upload', formData)
    noteEdit.value.coverImg = res.data.url
    ElMessage.success('封面设置成功')
  } catch { ElMessage.error('封面上传失败') }
}

onMounted(() => {
  fetchRouteTitle()
  fetchNotes()
})
</script>

<template>
  <div class="note-bg">
    <!-- 顶部Banner -->
    <div class="note-banner" :style="{backgroundImage: 'url(' + (routeCoverUrl || defaultBanner) + ')'}">
      <div class="banner-overlay"></div>
      <div class="banner-content">
        <span class="route-title">{{ routeTitle }}</span>
      </div>
    </div>
    <el-card class="note-main-card">
      <el-button type="default" @click="back" icon="el-icon-arrow-left" style="margin-bottom:14px;">
        返回路线广场
      </el-button>
      <div class="note-main-flex">
        <!-- 左侧卡片列表 -->
        <div class="note-side-list">
          <el-scrollbar height="570px">
            <div v-for="note in notes" :key="note.id"
                 :class="['note-card', selectedNoteId===note.id && 'note-card-active']"
                 @click="selectNote(note.id)">
              <img class="note-thumb" :src="note.coverImg || defaultThumb" />
              <div class="note-card-body">
                <div class="note-card-title">{{ note.title }}</div>
                <div class="note-card-meta">
                  <span class="note-card-date">{{ note.createTime?.slice(0,16) }}</span>
                </div>
                <div class="note-card-preview">
                  {{ note.content?.replace(/[#\-\*\[\]\(\)`>]/g,'').slice(0,40) }}...
                </div>
              </div>
              <el-dropdown style="margin-left:auto;">
                <span class="el-dropdown-link">
                  <el-icon><More /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click.stop="editNote(note)">编辑</el-dropdown-item>
                    <el-dropdown-item divided @click.stop="deleteNote(note.id)" style="color:red;">
                      <el-icon><Delete /></el-icon> 删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <el-button class="add-note-btn" type="primary" @click="newNote">
              <el-icon><Plus /></el-icon> 新建笔记
            </el-button>
          </el-scrollbar>
        </div>
        <!-- 右侧内容/编辑区 -->
        <div class="note-content-area">
          <el-empty v-if="!selectedNote && !showNoteEditor" description="请选择左侧笔记或新建一条" />
          <!-- 新建/编辑 -->
          <div v-if="showNoteEditor" class="note-editor-area">
            <el-form :model="noteEdit" label-width="68px">
              <el-form-item label="标题">
                <el-input v-model="noteEdit.title" placeholder="请输入笔记标题" />
              </el-form-item>
              <el-form-item label="封面">
                <input type="file" @change="uploadNoteCover" accept="image/*" />
                <img v-if="noteEdit.coverImg" :src="noteEdit.coverImg" style="width:80px;border-radius:7px;margin-top:8px;" />
              </el-form-item>
              <el-form-item label="内容">
                <v-md-editor
                    v-model="noteEdit.content"
                    height="480px"
                    :defaultShowPreview="false"
                    :upload-image="handleUploadImage"
                    :autoFocus="true"
                    placeholder="支持Markdown、图片、公式、代码块、海量文本编辑。"
                    style="margin-bottom:16px;"
                />
              </el-form-item>
              <el-form-item label="附件">
                <el-upload
                    :auto-upload="true"
                    :show-file-list="false"
                    :http-request="handleFileUpload"
                    accept=".doc,.docx,.pdf,.ppt,.pptx"
                >
                  <el-button size="small">上传附件</el-button>
                </el-upload>
                <div v-if="noteEdit.attachments && noteEdit.attachments.length" class="file-list">
                  <div v-for="(file, idx) in noteEdit.attachments" :key="file.url" class="file-item">
                    <a :href="file.url" target="_blank">{{ file.name }}</a>
                    <el-icon @click="removeAttachment(idx)" style="cursor:pointer;color:#f35;margin-left:6px;">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveNote">保存</el-button>
                <el-button @click="showNoteEditor = false">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
          <!-- 只读展示 -->
          <div v-else-if="selectedNote" class="note-readonly-area">
            <img v-if="selectedNote.coverImg" :src="selectedNote.coverImg" class="note-content-cover"/>
            <h2 class="note-title-view">{{ selectedNote.title }}</h2>
            <div class="note-date-view">创建时间：{{ selectedNote.createTime?.slice(0,16) }}</div>
            <div class="note-content-view">
              <v-md-preview :text="selectedNote.content" />
            </div>
            <div v-if="selectedNote.attachments && selectedNote.attachments.length" class="file-list-view">
              <el-divider content-position="left">
                <el-icon><Paperclip /></el-icon> 附件
              </el-divider>
              <div v-for="file in selectedNote.attachments" :key="file.url" class="file-item">
                <a :href="file.url" target="_blank">{{ file.name }}</a>
              </div>
            </div>
            <div style="margin-top:32px;">
              <el-button type="primary" @click="editNote(selectedNote)">编辑</el-button>
              <el-button type="danger" @click="deleteNote(selectedNote.id)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>



<style scoped>
.note-bg {
  min-height: 100vh;
  background: linear-gradient(120deg, #eef1f6 0%, #f4f7fb 100%);
  padding-bottom: 28px;
}
.note-banner {
  height: 220px;
  background-size: cover;
  background-position: center 60%;
  border-radius: 0 0 36px 36px;
  position: relative;
  margin-bottom: 24px;
  box-shadow: 0 5px 24px 0 rgba(120,140,200,0.12);
  display: flex;
  align-items: flex-end;
}
.banner-overlay {
  position: absolute;
  width: 100%; height: 100%;
  background: rgba(55,74,110,0.17);
  border-radius: 0 0 36px 36px;
  z-index: 1;
}
.banner-content {
  position: relative; z-index: 2;
  display: flex; align-items: center;
  padding: 0 58px 28px 54px;
}
.route-title {
  font-size: 2.32rem; font-weight: bold; color: #fff;
  letter-spacing:3px; text-shadow: 0 2px 8px #0002, 0 5px 12px #0004;
}
.note-main-card {
  max-width: 1160px;
  margin: 0 auto; border-radius: 22px; padding: 0;
  background: #fff; min-height: 640px;
  box-shadow: 0 2px 24px rgba(80,120,240,0.10);
}
.note-main-flex { display: flex; min-height: 550px; }
.note-side-list {
  width: 330px;
  background: #f8fafc; border-right:2px solid #e7e9f1;
  padding: 32px 12px 28px 22px;
  box-sizing: border-box;
}
.note-card {
  display: flex; align-items: flex-start; gap:14px;
  background: #fff; border-radius: 16px;
  margin-bottom: 20px; cursor: pointer;
  transition: box-shadow 0.25s, border 0.25s;
  border: 2px solid transparent; box-shadow:0 1px 7px #edf1f3;
  min-height: 90px; padding:14px 13px 11px 13px;
  position: relative;
}
.note-card:hover {
  border: 2px solid #63a7ff; box-shadow: 0 3px 18px #b7d2ff;
}
.note-card-active {
  border: 2.2px solid #397aff;
  box-shadow: 0 4px 18px #b7d2ff;
}
.note-thumb {
  width: 54px; height: 54px; border-radius: 10px; background: #f0f3f8;
  object-fit: cover; margin-right:6px; flex-shrink: 0;
}
.note-card-body { flex: 1; min-width: 0; }
.note-card-title {
  font-weight: 700; font-size: 1.16rem; color: #18366a;
  margin-bottom: 2px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
}
.note-card-meta {
  font-size: 12px; color: #a8b4c6; margin-bottom:2px;
}
.note-card-preview {
  font-size: 13px; color: #7a8baa; line-height: 1.6; overflow: hidden;
  text-overflow: ellipsis; max-width:180px; white-space: nowrap;
}
.add-note-btn {
  width: 100%; margin-top: 32px;
  border-radius: 10px; font-size: 17px; letter-spacing:2px;
}
.note-content-area {
  flex:1; padding: 48px 60px 38px 46px; background: #fff;
  min-height: 600px; border-radius: 0 22px 22px 0;
  display: flex; flex-direction: column;
  overflow-y: auto;
}
.note-content-cover {
  width: 120px; border-radius: 15px; box-shadow: 0 2px 12px #eceef1;
  margin-bottom: 26px;
}
.note-title-view {
  font-size: 2.2rem;
  font-weight: 700;
  color: #26367e;
  margin-bottom: 20px;
  letter-spacing:1.2px;
}
.note-date-view {
  font-size: 13px;
  color: #aaa;
  margin-bottom: 22px;
}
.note-content-view {
  font-size: 1.19rem;
  color: #384468;
  line-height: 1.9;
  padding: 12px 8px 0 8px;
  background: #f7f8fc;
  border-radius: 8px;
  min-height: 120px;
  word-break: break-all;
  max-height: 480px;
  overflow-y: auto;
}
.note-editor-area {
  max-width: 820px;
}
.note-readonly-area {
  max-width: 820px;
}
.file-list, .file-list-view { margin: 10px 0 0 0; }
.file-item {
  display: flex; align-items: center;
  margin: 2px 0; gap: 8px; font-size: 14px;
}
@media (max-width: 1300px) {
  .note-main-card, .note-banner { max-width: 99vw; }
  .note-content-area { padding: 22px 2vw; }
}
@media (max-width: 900px) {
  .note-main-flex { flex-direction: column; }
  .note-side-list { width: 100vw; min-width: unset; border-right: none; border-bottom: 1px solid #f1f3f8; }
  .note-content-area { border-radius: 0 0 22px 22px; min-height: 380px; }
  .note-banner { height: 110px; }
  .banner-content { padding: 0 12vw 12px 8vw; }
  .route-title { font-size: 1.5rem; }
}
</style>